package com.zz.demo.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionLock {
    public static void main(String[] args) throws InterruptedException {
        MyCondition myCondition = new MyCondition();
        Thread thread1 = new Thread(myCondition, "第一个线程");
        thread1.start();
        Thread.sleep(3000);
        myCondition.signal();
    }
}

/**
 * 使用Condition来实现等待和通知
 */
class MyCondition implements Runnable {
    private Lock lock = new ReentrantLock();
    public Condition condition = lock.newCondition();

    @Override
    public void run() {
        System.out.println("当前线程名：" + Thread.currentThread().getName() + "开始等待时间：" + System.currentTimeMillis());
        // 线程等待
        try {
            lock.lock();
            //先给线程上锁，然后才能获取监视器。
            System.out.println("我陷入了等待。。。");

            condition.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println("锁释放了");
        }
    }

    /**
     * 通知方法
     */
    public void signal() {
        try {
            lock.lock();
            System.out.println("结束等待时间：" + System.currentTimeMillis());
            //通知等待线程
            condition.signal();
        } finally {
            lock.unlock();
        }

    }
}